﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common.Utils.UDPHelps
{
    public class MulticastCommunicate
    {
        private UdpClient m_UdpClient;

        private IPEndPoint m_receivIpEndPoint;


        private Task m_Task;

        /// <summary>
        /// 收到数据包后事件
        /// </summary>
        public event Action<byte[]> ReceivedPacket;




        public void Init(IPEndPoint receivEndPoint)
        {
            //广播 广播不需要端口号
            m_UdpClient = new UdpClient();
            //m_UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            m_UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 300_000);
            m_UdpClient.Client.ReceiveBufferSize = 300_000;
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, receivEndPoint.Port);
            m_receivIpEndPoint= ipEndPoint;
            m_UdpClient.Client.Bind(ipEndPoint);
            //自发自收
            m_UdpClient.EnableBroadcast = true;
            //组播
            m_UdpClient.MulticastLoopback = true;
            m_UdpClient.JoinMulticastGroup(receivEndPoint.Address);
            m_Task = new Task(ThreadStart);
            m_Task.Start();
        }

        public void Init2(int port)
        {
            //广播 
            m_Task = new Task(RecvThread, port);
            m_Task.Start();
        }

         void RecvThread(object port)
        {
            UdpClient UDPrece = new UdpClient(new IPEndPoint(IPAddress.Any, int.Parse(port.ToString())));
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                byte[] buf = UDPrece.Receive(ref endpoint);
                if (ReceivedPacket != null)
                {
                    ReceivedPacket(buf);
                }
                //Console.WriteLine(msg);
            }
        }

        private void ThreadStart()
        {
            try
            {
                byte[] data;
                while (true)
                {
                    try
                    {
                        data = m_UdpClient.Receive(ref m_receivIpEndPoint);
                        if (ReceivedPacket != null)
                        {
                            ReceivedPacket(data);
                        }
                    }
                    catch (Exception exception)
                    {
                        //MessageBox.Show(exception.Message);
                    }
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }
        }
    }
}
